package com.stone.im.geteway.websocket;

import io.netty.channel.socket.SocketChannel;

import java.util.concurrent.ConcurrentHashMap;

/**
 * 管理netty长连接的组件
 */
public class NettyChannelManager {

    /**
     * 内部类单例模式
     */
    static class Singleton{
        static NettyChannelManager instance = new NettyChannelManager();
    }

    /**
     * 存储所有的客户端连接
     */
    private ConcurrentHashMap<String, SocketChannel> channels = new ConcurrentHashMap<String, SocketChannel>();

    /**
     * 保存客户端的id
     */
    public ConcurrentHashMap<String,String> channelIds = new ConcurrentHashMap<String, String>();

    /**
     * 添加socketchannel
     * @param key
     * @param channel
     */
    public void addChannel(String key, SocketChannel channel) {
        channelIds.put(channel.remoteAddress().getHostName(),key);
        channels.put(key, channel);
    }

    /**
     * 获取实例
     * @return
     */
    public static NettyChannelManager getInstance() {
        return Singleton.instance;
    }

    /**
     * 判断是否存在某个客户端
     * @param key
     * @return
     */
    public Boolean existChannel(String key) {
        return channels.containsKey(key);
    }

    /**
     * 获取某个用户的连接
     * @param key
     * @return
     */
    public SocketChannel getChannel(String key) {
        return channels.get(key);
    }

    public void removeChannel(SocketChannel channel){
        channelIds.remove(channel.remoteAddress().getHostName());
        channels.remove(channelIds.get(channel.remoteAddress().getHostName()));
    }

}
